package fu.capstone.hanoicityguide.presentation.fragment.attraction;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBO;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBOImp;
import fu.capstone.hanoicityguide.business.model.Attraction;
import fu.capstone.hanoicityguide.business.model.Category;
import fu.capstone.hanoicityguide.presentation.adapter.ListAttractionAdapter;

@SuppressLint("ValidFragment")
public class ListAttractionFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private AttractionBO attractionBO;
	private ArrayList<Attraction> arrAttraction;
	private String[] arrType;
	private ArrayList<Category> arrCategory = null;
	private ArrayList<String> filter;
	private String sorter;
	private ListAttractionAdapter attractionAdapter = null;
	private ListView listAttraction = null;
	private SearchView searchView;
	private String keyword;
	private boolean[] itemChecked;
	private boolean[] oldChecked;
	private DrawerLayout drawer;

	public ListAttractionFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// init
		try {
			setHasOptionsMenu(true);
		} catch (Exception e) {
			Log.e("List Attraction Fragment", e.toString());
		}
		View listAttractionFragment = inflater.inflate(
				R.layout.fragment_list_attraction, container, false);
		attractionBO = new AttractionBOImp(container.getContext());
		listAttraction = (ListView) listAttractionFragment
				.findViewById(R.id.listAttraction);

		// set filter and sorter
		filter = new ArrayList<String>();
		setKeyword("");
		// setFilter("All");
		setSorter(getResources().getStringArray(R.array.sorter_items)[0]);

		// get category
		arrCategory = new ArrayList<Category>();
		arrCategory = attractionBO.getListCategory("Attraction");

		if (arrCategory.size() > 0) {
			// get all category to filter
			arrType = attractionBO.getListType(arrCategory.get(0).getId());
		}

		for (int i = 1; i < arrType.length; i++) {
			filter.add(arrType[i]);
		}

		// init checked item
		itemChecked = new boolean[arrType.length];
		for (int i = 0; i < itemChecked.length; i++) {
			itemChecked[i] = true;
		}

		// get all list attraction
		arrAttraction = new ArrayList<Attraction>();
		arrAttraction = attractionBO.listAttraction(getFilter(), getSorter());

		attractionAdapter = new ListAttractionAdapter(getActivity(),
				R.layout.adapter_list_attraction, arrAttraction);

		// set listview adapter and create event for items click
		listAttraction.setAdapter(attractionAdapter);

		listAttraction.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// call DetailAttractionFragment
				Fragment browseAttraction = new DetailAttractionFragment(
						arrAttraction.get(position).getId());
				if (browseAttraction != null) {
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fTransaction = fragmentManager
							.beginTransaction();
					fTransaction.addToBackStack(null);
					fTransaction
							.replace(R.id.frame_container, browseAttraction)
							.commit();
					getActivity().setTitle(
							arrAttraction.get(position).getName());
				}
			}
		});
		return listAttractionFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_attraction_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_attraction)
				.getActionView();
		setupSearchView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;

		switch (item.getItemId()) {
		// show filter dialog
		case R.id.action_filter_attraction:

			builder.setTitle("Filter");
			builder.setCancelable(false);
			oldChecked = new boolean[itemChecked.length];
			for (int i = 0; i < oldChecked.length; i++) {
				oldChecked[i] = itemChecked[i];
			}
			// set event for check item
			builder.setMultiChoiceItems(arrType, itemChecked,
					new DialogInterface.OnMultiChoiceClickListener() {

						@Override
						public void onClick(DialogInterface dialog,
								int indexSelected, boolean isChecked) {
							AlertDialog alert = (AlertDialog) dialog;
							ListView list = alert.getListView();
							// check item
							if (isChecked) {
								// checked all
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, true);
										itemChecked[i] = true;
									}
								}
								// checked 1 item
								else {
									boolean checkAll = false;
									itemChecked[indexSelected] = true;
									// check all item
									for (int i = 1; i < itemChecked.length; i++) {
										if (itemChecked[i] == false) {
											checkAll = false;
											break;
										} else {
											checkAll = true;
										}
									}
									if (checkAll) {
										list.setItemChecked(0, true);
										itemChecked[0] = true;
									}
								}

							} else {
								// uncheck item
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, false);
										itemChecked[i] = false;
									}
								} else {
									list.setItemChecked(0, false);
									itemChecked[0] = false;
									itemChecked[indexSelected] = false;
								}
							}
						}
					});

			// Set the action buttons
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// set filter
							filter = new ArrayList<String>();
							for (int i = 1; i < itemChecked.length; i++) {
								if (itemChecked[i]) {
									filter.add(arrType[i]);
								}
							}

							// get list attraction from db
							if ("".equals(getKeyword())) {
								arrAttraction = attractionBO.listAttraction(
										getFilter(), getSorter());
							} else {
								arrAttraction = attractionBO.searchAttraction(
										getKeyword(), getFilter(), getSorter());
							}

							attractionAdapter.setArr(arrAttraction);
							attractionAdapter.notifyDataSetChanged();
						}
					});
			builder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// Your code when user clicked on Cancel
							for (int i = 0; i < oldChecked.length; i++) {
								itemChecked[i] = oldChecked[i];
							}
						}
					});

			dialog = builder.create();
			dialog.show();
			break;
		case R.id.action_sort_attraction:
			// String[] arrSorter = new String[4];
			builder.setTitle("Sort");
			builder.setItems(getResources()
					.getStringArray(R.array.sorter_items),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int item) {
							// sort by sorter
							setSorter(getResources().getStringArray(
									R.array.sorter_items)[item]);
							if ("".equals(getKeyword())) {
								arrAttraction = attractionBO.listAttraction(
										getFilter(), getSorter());
							} else {
								arrAttraction = attractionBO.searchAttraction(
										getKeyword(), getFilter(), getSorter());
							}
							// reset array attraction in adapter
							attractionAdapter.setArr(arrAttraction);
							attractionAdapter.notifyDataSetChanged();
						}
					});

			dialog = builder.create();
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to Attractions
		super.onResume();
		getActivity().getActionBar().setTitle("Attractions");
	}

	public ArrayList<String> getFilter() {
		return this.filter;
	}

	// public void setFilter(String filter) {
	// this.filter = filter;
	// }

	public String getSorter() {
		return this.sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Attraction Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getFilter() != null && getSorter() != null) {
			arrAttraction = attractionBO.searchAttraction(getKeyword(),
					getFilter(), getSorter());
			attractionAdapter.setArr(arrAttraction);
			attractionAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);
		if (getKeyword() != null && getFilter() != null && getSorter() != null) {
			arrAttraction = attractionBO.searchAttraction(getKeyword(),
					getFilter(), getSorter());
			attractionAdapter.setArr(arrAttraction);
			attractionAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		searchView.setQuery("", true);
		setKeyword("");
		arrAttraction = attractionBO.searchAttraction("", getFilter(),
				getSorter());
		attractionAdapter.setArr(arrAttraction);
		attractionAdapter.notifyDataSetChanged();
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

}
